#!/bin/bash -x

set +e

which git >/dev/null

URL="http://downloads.arduino.cc/arduino-nightly-linux64.tar.xz"
# URL="http://downloads.arduino.cc/arduino-1.6.8-linux64.tar.xz"
APP=Arduino
mkdir -p ./$APP
cd ./$APP

wget -q https://github.com/AppImage/AppImages/raw/master/functions.sh -O ./functions.sh
. ./functions.sh

wget -c "$URL"
tar xf *.tar.xz

mkdir -p $APP.AppDir/usr/bin

mv ardu*/* $APP.AppDir/usr/bin/

cd $APP.AppDir/

get_apprun

# Move icons into place so that AppImageAssistant finds them
mkdir -p usr/share/icons
mv usr/bin/lib/icons usr/share/icons/hicolor
cat usr/share/icons/hicolor/128x128/apps/arduino.png > arduino.png
rm -rf ./usr/share/icons/hicolor/48x48

# Get appdata - why is it missing in the binary distribution?
mkdir -p usr/share/metainfo/
rm usr/share/metainfo/arduino.appdata.xml || true
wget -c "https://github.com/arduino/Arduino/raw/master/build/linux/dist/appdata.xml" -O usr/share/metainfo/arduino.appdata.xml

# Get desktop file
find . -name desktop.template -exec cp {} arduino.desktop \;
sed -i -e 's/<BINARY_LOCATION>/arduino/g' arduino.desktop
sed -i -e 's/<ICON_NAME>/arduino/g' arduino.desktop

# Add git version of https://github.com/esp8266/Arduino/
git clone https://github.com/esp8266/Arduino.git usr/bin/hardware/esp8266/esp8266/ 
cd usr/bin/hardware/esp8266/esp8266/tools/
python ./get.py
ESPVER=$(git rev-parse --short HEAD)
sed -i  -r "s|^name=.*?|name=ESP8266 Modules (git $ESPVER)|g" ../platform.txt
rm ./dist/*
cd ../../../../../../

# Add Arduino ESP8266 filesystem uploader
cd usr/bin/tools/
DLD=$(wget -q "https://github.com/esp8266/arduino-esp8266fs-plugin/releases/" -O - | grep ".zip" | head -n 1 | cut -d '"' -f 2)
wget -c "https://github.com/$DLD"
unzip ESP8266FS-*.zip
rm ESP8266FS-*.zip
cd ../../../

# Add desktop integration
XAPP=arduino
wget -O ./usr/bin/$XAPP.wrapper https://raw.githubusercontent.com/probonopd/AppImageKit/master/desktopintegration
chmod a+x ./usr/bin/$XAPP.wrapper
sed -i -e "s|Exec=$XAPP|Exec=$XAPP.wrapper|g" $XAPP.desktop

cd .. # Go out of AppDir

# Figure out $VERSION
VER=$(grep -r ARDUINO $APP.AppDir/usr/bin/revisions.txt | head -n 1 | cut -d " " -f 2)
HOUR=$(cat $APP.AppDir/usr/bin/lib/hourlyBuild.txt | sed -e 's|/||g' | sed -e 's| ||g' | sed -e 's|:||g')
VERSION=$VER".hourly"$HOUR".esp"$ESPVER
echo $VERSION

generate_type2_appimage
